import Util from "../../utils/util";
import {getActivitPostList, getActivityDetail} from "../../api/activity";

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    parameter: {
      title: "",
      isBack: true,
    },
    opacity: 0,
    fields: {
      type: {title: "类型"},
      address: {title: "地点", hide: true},
      start_time: {title: "活动时间"},
      subject: {title: "关联学科"},
      score: {title: "难度"},
      sdgs: {title: "SDGs"},
      join_age: {title: "适合龄段"},
    },

    tabNavs: [
      "活动简介",
      "活动详情",
      "伙伴反馈",
    ],
    tabIndex: 0,

    loading: false, // 是否加载中
    loadend: false, // 是否加载完毕
    loadTitle: '加载更多内容', // 提示语
    postList: [],
    page: 1,
    et_show: true,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    this.setData({
      bottom: 30,
      activity_id: options.id || 0,
      navH: app.globalData.navHeight
    })

    if (Util.isEmpty(this.data.activity_id)) {
      if (getCurrentPages().length > 1) {
        Util.Tips({title: errmsg}, {tab: 1})
      } else {
        Util.Tips({title: errmsg}, {tab: 4, url: "/pages/activity/index"})
      }
      return;
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    Util.chekWxLogin().then(res => {
      that.setData({
        userInfo: res.userInfo || null
      })

      wx.showLoading({title: '正在加载...'});
      getActivityDetail(that.data.activity_id).then(res => {
        that.setData({...res.data});

        let activity = that.data.activity || null;
        if (Util.isEmpty(activity))
          return;

        activity['subject_title'] = activity.subject_title ? activity.subject_title.join(' ') : "";
        activity['sdgs_title'] = activity.sdgs_title ? activity.sdgs_title.join(' ') : "";

        let nums = [];
        for (let i = 0; i < parseInt(activity.score || 0); i++) {
          nums.push(i)
        }
        activity.score_nums = nums;
        that.setData({
          activity: activity,
        })

        if (parseInt(activity.is_online || 0) === 1) {
          let fields = that.data.fields;
          fields['address'].hide = false;
          that.setData({fields: fields})
        }

      }).catch(errmsg => {
        Util.Tips({title: errmsg}, {tab: 3})
      }).finally(() => {
        that.onLoadTabbar();
        wx.hideLoading();
      })
    })
  },

  changeTab(e) {
    const that = this,
      index = e.currentTarget.dataset.index;
    if (index === that.data.tabIndex)
      return;

    that.setData({
      tabIndex: index
    })

    if (this.data.tabIndex == 2) {
      this.getPostLists();
    }
  },

  makePhoneCall(e) {
    const v = e.currentTarget.dataset.mobile;
    wx.makePhoneCall({
      phoneNumber: v,
      success: function () {
        console.log('拨打成功');
      },
      fail: function () {
        Util.Tips({title: "呼叫失败，请联系管理员！", hideMask: true});
      }
    });
  },

  goToSign(e) { //去报名

    const that = this,
      activity = that.data.activity,
      member = that.data.userInfo || null;

    if (activity.status !== 1)
      return Util.Tips({title: "活动未开始", hideMask: true});

    if (Util.isEmpty(member.username) || Util.isEmpty(member.gender) || Util.isEmpty(member.avatar)) {
      Util.showModelTip("你的资料还没有完善，请先完善基本资料", "", "去完善", "取消")
        .then(res => {
          if (res.confirm) {
            wx.navigateTo({
              url: "../member/edit"
            });
          }
        })
      return;
    }
    wx.navigateTo({
      url: "../activity/sign?id=" + this.data.activity_id
    })
  },

  getPostLists() {//伙伴反馈
    const that = this
    if (that.data.loadend || that.data.loading) {
      return;
    }

    let filter = that.data.filter || {}
    filter['page_num'] = that.data.page;
    filter['activity_id'] = that.data.activity_id;

    that.setData({loading: true, loadTitle: '正在加载...'});
    let lists = that.data.postList || []
    getActivitPostList(filter).then(res => {
      const list = res.data.items || []
      const loadend = res.data.last_page <= that.data.page;
      lists = Util.SplitArray(list, lists);

      that.setData({
        postList: lists,
        loadend: loadend,
        loading: false,
        loadTitle: loadend ? '已全部加载' : '正在加载...',
        total: res.data.total,
        page: that.data.page + 1,
        et_show: lists.length > 0
      });

    }).catch(errmsg => {
      Util.Tips({title: errmsg})
    }).finally(() => {
      wx.stopPullDownRefresh()
    })

  },

  onPageScroll(e) {
    const that = this
    let r = e.scrollTop / 100;
    this.setData({
      opacity: r >= 1 ? 1 : r
    })
  },

  goBack(e) {
    let pages = getCurrentPages();
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({
        url: '/pages/activity/index'
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (parseInt(this.data.tabIndex || 0) === 2) {
      this.getPostLists();
    }
  },
  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this
    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({
        isIphoneX: res,
      })
    }).finally(() => {
      wx.createSelectorQuery().in(that).select('.weui-footer')
        .boundingClientRect(function (rect) {
          that.setData({
            bottom: parseInt(rect.height) + 15
          })
        }).exec()
    });
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})